package org.dant.ant.extension.net.processors;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintStream;
import java.io.StringReader;

import org.apache.tools.ant.util.StringUtils;
import org.apache.tools.ant.util.DateUtils;
import org.apache.tools.ant.BuildEvent;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.BuildLogger;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DefaultLogger;

public class RemoteLogger extends DefaultLogger {
  
  protected StringBuffer outBuffer = new StringBuffer();
  protected StringBuffer errBuffer = new StringBuffer();
  protected String target = null;
  private boolean newTarget = true;
  
  public RemoteLogger() {
  }

  public void setTarget(String target) {
    this.target = target;
  }

  public void targetStarted(BuildEvent event) {
    if (!target.equals(event.getTarget().getName())) {
      return;
    }
    log("<" + event.getTarget() + "> target started");
    if (Project.MSG_INFO <= msgOutputLevel) {
      String msg = StringUtils.LINE_SEP 
        + event.getTarget().getName() + ":";
      printMessage(msg, out, event.getPriority());
      log(msg);
    }
    newTarget = false;
  }
  
  public void targetFinished(BuildEvent event) {
    newTarget = true;
    if (!target.equals(event.getTarget().getName())) {
      return;
    }
    log("<" + event.getTarget() + "> target finished");
  }
  
  public void taskStarted(BuildEvent event) {}
  
  public void taskFinished(BuildEvent event) {}
  
  public void messageLogged(BuildEvent event) {
    if (event.getTarget() == null)  return;
    if (!target.equals(event.getTarget().getName())) {
      return ;
    }
    
    log(event.getMessage());
  }
  
  protected void log(String message) {
    if (!newTarget) {
      outBuffer.append("\t");
    }
    outBuffer.append(message);
    outBuffer.append("\n");
  }

  public StringBuffer getOutBuffer() {
    return outBuffer;
  }
}

